const sequelize = require('../sequlize-config');
const Sequelize = require('sequelize');
let Activities = require('../model/Activities');
let Participant = require('../model/Participant');
let printLog = require('../log4j-config');
//sequlize中封装的sql运算符,应该是个Symbol对象
const Op = Sequelize.Op;
//将两张表查询到的数据组合成一个[{aid, title...., people: []},{aid1, title...., people1:[]}]格式的JSON对象
const assemebleJSON = (activities = [], people = []) => {
    for (let i = 0; i < people.length; i++) {
        let nowPeople = people[i];
        for (let j = 0; j < activities.length; j++) {
            let nowActivity = activities[j];
            nowActivity.dataValues.people = nowActivity.dataValues.people || [];
            if (nowActivity.aid === nowPeople.aid) {
                nowActivity.dataValues.people.push(nowPeople);
                break;
            }
        }
    }
}
//这个地方的SQL逻辑比较复杂，目前是简化了SQL查询逻辑，将数据处理部分放在了服务端上。
//如果会写存储过程可以写存储过程来简化服务端的操作提高效率。
//第一次请求在600ms左右，感觉是因为客户端和服务器keep alive断开的原因
module.exports = {
    getAllActivity: function (req, res) {
        (async () => {
            try {
                let activities = await Activities.findAll();
                let people = await Participant.findAll();
                assemebleJSON(activities, people);
                printLog.INFO(`SELECT all activities info success at IP : ${req.host}`)
                res.status(200).send({ succeed: true, activities: activities })
            } catch (err) {
                printLog.ERROR(`ERROR on SELECT all activities info success at IP : ${req.host}`)
                res.status(400).send({ succeed: false, err: err })
            }
        })()
    },
    getThisWeekActivity: function (req, res) {
        let thisWeekActivities = [],
            aids = [],
            people = [];
        (async () => {
            try {
                //这个地方直接写SQL语句去查，因为ORM框架组装和调用数据库的函数比较耗时
                thisWeekActivities = await sequelize.query('SELECT * FROM activities WHERE WEEK(time, 1)=WEEK(NOW(), 1)', { model: Activities })
                if (thisWeekActivities.length > 0) {
                    thisWeekActivities.forEach(function (value, item) {
                        value.dataValues.people = [];
                        aids.push({ aid: value.aid });
                    });
                    people = await Participant.findAll({
                        where: {
                            [Op.or]: aids
                        }
                    });
                    assemebleJSON(thisWeekActivities, people)
                }
                printLog.INFO(`SELECT activity info success at IP : ${req.host}`)
                res.status(200).send({ succeed: true, activities: thisWeekActivities })
            } catch (err) {
                printLog.ERROR(`ERROR on SELECT activity info success at IP : ${req.host}`)
                res.status(400).send({ succeed: false, err: err })
            }
        })()
    },
    todayHasActvity: function (req, res) {
        // sequelize.query('SELECT * FROM activities WHERE TO_DAYS(time)=TO_DAYS(NOW()) LIMIT 1')
        //          .then(function(data) {
        //              debugger;
        //          })

    }
}